#!/usr/bin/env python

import os
import sys


def _test(results, environ, atest):
    print '\nLoad atest file: %s ...' % atest

    import at_xml

    xmlp = at_xml.Parser(environ)
    cases = xmlp.parse(atest)
    print '%d case(s) found in the file %s' % (len(cases), atest)

    import at_exec
    executor = at_exec.Executor(environ)

    for c in cases:
        name = getattr(c, 'name', '')
        print '\n================================'
        print 'Run case %s' % name

        result = results.addCase(name)
        ret = executor.execute(result, c)
        print
        print 'Result: %s' % result.getResult()


def main(dirs=None):
    cwp = os.path.realpath(os.getcwd())
    root = os.path.realpath(os.path.dirname(cwp))

    # add the core path
    sys.path.append(os.path.join(cwp, 'atest'))
    sys.path.append(os.path.join(root, 'anafile'))

    import at_env
    environ = at_env.Environ({'APP_ROOT': root})

    if len(dirs or '') == 0:
        dirs = [cwp]

    fileset = list()
    for d in dirs:
        rd = os.path.realpath(d)
        for rroot, dirs, files in os.walk(rd):
            for f in files:
                if f == 'atest.xml':
                    fileset.append(os.path.join(rroot, f))

    import at_results
    resultset = at_results.Resultset()

    for f in fileset:
        path = os.path.dirname(f)
        os.chdir(path)

        results = resultset.addFile(f)
        _test(results, environ, f)

        os.chdir(root)

    print
    print resultset


if __name__ == '__main__':
    main(sys.argv[1:])
